<?php

namespace addons\kzvote\controller;

use addons\kzvote\library\Poster;
use addons\kzvote\library\WechatSubscription;
use addons\kzvote\model\MusicModel;
use addons\kzvote\library\Subscription;
use app\common\model\kzvote\gift\Order;
use app\common\model\kzvote\Log;
use app\common\model\kzvote\Person as PersonModel;
use app\common\model\kzvote\Vote as VoteModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use think\Exception;

/**
 * 作品接口
 */
class Person extends Base
{
    protected $noNeedLogin = ['index', 'detail', 'poster'];

    /**
     * 作品列表
     */
    public function index()
    {
        $vote_id = $this->request->request('vote_id');
        $status = $this->request->request('status', '20');
        $group_id = $this->request->request('group_id', '');
        $keyword = $this->request->param('keyword');
        $order = $this->request->request('order', 'code');
        $VotePerson = new PersonModel();
        if ($group_id) {
            $VotePerson->where('group_id', $group_id);
        }
        if ($keyword) {
            $VotePerson->where('name|code', 'like', "%{$keyword}%");
        }
        if ($order == 'code') {
            $VotePerson->order('code asc');
        } else {
            $orderArr = [$order => 'desc'];
            if($order == 'count'){
                //如果是按照投票数排名则再加上最后达成时间的因素进行排名
                $orderArr['last_vote_time'] = "asc";
            }
            $VotePerson->order($orderArr);
        }
        $person = $VotePerson->where(['status' => $status, 'vote_id' => $vote_id])
            ->paginate(20, true);
        $this->success('排名有一场',$person);
    }

    /**
     * 作品统计
     */
    public function count()
    {
        $vote_id = $this->request->request('vote_id');
        $VotePerson = new PersonModel();
        $data['status10'] = $VotePerson->where(['status' => '10', 'vote_id' => $vote_id])->count();
        $data['status20'] = $VotePerson->where(['status' => '20', 'vote_id' => $vote_id])->count();
        $data['status30'] = $VotePerson->where(['status' => '30', 'vote_id' => $vote_id])->count();
        $this->success('',$data);
    }

    /**
     * 作品详情
     */
    public function detail()
    {
        $id = $this->request->param('id');
        $manage = $this->request->param('manage',0);
        $detail = PersonModel::get($id, ['vote']);
        if (!$detail) {
            $this->error('数据不存在');
        }
        if (!$manage && $detail->status != '20') {
            $this->error('作品未通过审核');
        }
        if ($detail['vote']['option']) {
            $detail['vote']['option'] = explode(',', $detail['vote']['option']);
        }
        if ($detail['vote']['join_form']) {
            $detail['vote']['join_form'] = explode(',', $detail['vote']['join_form']);
        }
        if ($detail['music_id']) {
            $detail->append(['music']);
        } else {
            $detail['music'] = MusicModel::where('id', $detail['vote']['music_id'])->find();
        }
        $detail['images'] = explode(',', $detail['images']);
        $rankCondition = [
            'count' => ['>', $detail['count']],
            'vote_id' => $detail['vote_id']
        ];
        if($detail['vote']["apply_check"] == 1){
            $rankCondition['status'] = '20';
        }
        $largeCount = PersonModel::where($rankCondition)->count();
        $rankCondition['count'] = $detail['count'];
        $rankCondition['last_vote_time'] = ['<', $detail['last_vote_time']];
        $equalCount = PersonModel::where($rankCondition)->count();
        $detail['paiming'] = $largeCount+$equalCount+1;

        $data['order'] = Order::where('person_id', $id)->where('status', '20')
            ->field('nickname,person_id,id,name,num,image,status')
            ->limit(20)
            ->order("id desc")
            ->select();
        $data['person'] = $detail;

        //判断一下当前用户是否已经提交过表单
        if ($detail['vote']['join_form_status'] == '1'){
            $user = $this->auth->getUser();
            Log::where('vote_id',$detail['vote_id'])->where('user_id',$user['id'])
                ->where('person_id',$id)->where('join_form','<>','')
                ->find() ? $data['is_join_form'] = 1 : $data['is_join_form'] = 0;
        }

        $this->success('',$data);
    }

    /**
     * 删除作品
     */
    public function del()
    {
        $id  = $this->request->param('id');
        $person = PersonModel::get($id);
        if ($person->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 录入作品
     */
    public function save()
    {
        $post = $this->request->post();
        if (isset($post['id']) && $post['id'] > 0) {
            $PersonModel = PersonModel::get($post['id']);
        } else {
            unset($post['id']);
            $PersonModel = new PersonModel;
            //$count = $PersonModel->where(['vote_id' => $post['vote_id']])->where('status', '20')->count();
            $count = $PersonModel->where(['vote_id' => $post['vote_id']])->count();
            $post['code'] = $count + 1;
        }
        unset($post['er_code']);
        if ($PersonModel->allowField(true)->save($post)) {
            // 创建活动小程序码
            kzvote_qrCode($PersonModel, $PersonModel['id'], 'pages/vote/person');
            $this->success('保存成功');
        }
        $this->error('保存失败');
    }

    /**
     * 报名审批
     */
    public function status()
    {
        $id = $this->request->request('id');
        $status = $this->request->request('status');

        $person = PersonModel::get($id);
        $person->status = $status;
        if ($status == 20) {
            $count = (new PersonModel)->where('vote_id', $person['vote_id'])
                ->where('status', '20')->count();
            $person->code = $count + 1;
        }

        if ($person->save()) {
            $this->success('审核成功');
        }
        $this->error('审核失败');
    }

    /**
     * 投票按钮事件
     */
    public function vote()
    {
        $post = $this->request->post();

        $vote_id = $post['vote_id'] ?? 0;
        $person_id = $post['person_id'] ?? 0;
        // type==2时是看视频奖励票数
        $type = $post['type'] ?? 1;

        if (!$vote_id || !$person_id) {
            $this->error('参数异常');
        }

        $vote = VoteModel::get($vote_id);
        // 活动状态不是开始、审核不是通过、截止报名时间大于当前时间
        if ($vote['status'] != '10') {
            $this->error('当前活动已暂停或废弃');
        }
        if ($vote['check'] != '1') {
            $this->error('当前作品未通过审核');
        }
        if ($vote['start_time'] > time()) {
            $this->error('活动未开始');
        }
        if ($vote['status'] != '10' || $vote['check'] != '1' || $vote['start_time'] > time()) {
            $this->error('当前活动不允许参与');
        }
        if ($vote['end_time'] < time()) {
            $this->error('投票活动已结束');
        }

        $VotePerson = PersonModel::get($person_id);
        $user = $this->auth->getUser();
        if($vote['allow_support_self'] == '0' && $VotePerson->user_id == $user['id']){
            $this->error('不允许给自己投票');
        }

        $config = kzvote_getConfig('active');
        if ($this->platform == 'wxapp' && isset($config['vote_mobile_status']) && $config['vote_mobile_status'] == 1 && !$user['mobile']) {
            $this->error('需要绑定手机号');
        }

        $logCount = Log::where(['vote_id' => $vote_id, 'user_id' => $user['id'], 'type' => $type])->count();
        $log = Log::where(['vote_id' => $vote_id, 'user_id' => $user['id'], 'type' => $type])
            ->whereTime('createtime', 'today')
            ->column('person_id');

        /*
         * limit_count 用户投票总次数，0为不限制
         * day_limit_count 用户每日投票总次数
         * day_limit_status 允许单日同一项重复被投票开关 0只能投票1人 1可以投票多人
         * */
        if ($vote['limit_count'] > 0 && $vote['limit_count'] <= $logCount) {
            $this->error($type == 1 ? '超出总限制次数' : '超出总观看次数');
        }

        if ($vote['day_limit_count'] > 0 && $vote['day_limit_count'] <= count($log)) {
            $this->error($type == 1 ? '今日票数已投完，明日继续投票吧' : '今日观看次数已用完,明天再继续吧');
        }

        if ($vote['person_day_limit'] > 0) {
            $personDayLimit = Log::where(['vote_id' => $vote_id, 'user_id' => $user['id'], 'person_id' => $person_id, 'type' => $type])->whereTime('createtime', 'today')->count();
            if($vote['person_day_limit'] <= $personDayLimit){
                $this->error($type == 1 ? '今日票数已投完，明日继续投票吧' : '今日观看次数已用完,明天再继续吧');
            }
        }

        if ($vote['day_limit_status'] == 0 && $log) {
            if (in_array($person_id, $log)) {
                $this->error('不能投票给同1个选项');
            }
        }

        //获取用户IP
        if (isset($_SERVER)) {
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        }
        /*
        $count = Log::where('ip', $realip)->whereBetween('createtime', [time() - 1800, time()])->count();
        if ($count > 10) {
            $this->error('用户IP异常，请按照规则正确使用投票');
        }
        */
        Log::create([
            'admin_id' => $vote['admin_id'],
            'user_id' => $user['id'],
            'vote_id' => $vote_id,
            'person_id' => $person_id,
            'type' => $type,
            'num' => $type == 1 ? 1 : $vote['award_num'],
            'ip' => $realip,
            'join_form' => $post['join_form'],
        ]);
        $VotePerson->count = $VotePerson->count + 1;
        $VotePerson->last_vote_time = time();
        $VotePerson->save();

        // 发送订阅消息
        if ($post['send']){
            if ($vote['mold'] == '4'){
                $path = 'pages/vote/pk?vote_id=' . $vote_id;
            }else if ($vote['mold'] == '3'){

            }else{
                $path = 'pages/vote/person?person_id=' . $person_id;
            }
            if ($this->platform == 'wxapp') {
                Subscription::vote_result(kzvote_getOpenid($user['id'], $this->platform), $path, $vote['name'], $VotePerson['name'], $type == 1 ? 1 : $vote['award_num']);
            } elseif ($this->platform == 'wechat') {
                WechatSubscription::vote_result(kzvote_getOpenid($user['id'], $this->platform), $path, $vote['name'], $VotePerson['name'], $type == 1 ? 1 : $vote['award_num']);
            }
        }

        $this->success('投票成功');
    }

    /**
     * 检测是否已报名活动
     */
    public function apply_check()
    {
        $user = $this->auth->getUser();
        $vote_id = $this->request->param('vote_id');
        $person = PersonModel::get(['user_id' => $user['id'], 'vote_id' => $vote_id]);
        if ($person) {
            $person['images'] = explode(',', $person['images']);
        }
        $this->success('',$person);
    }

    /**
     * 获取报名活动的作品列表
     */
    public function user_persons()
    {
        $user = $this->auth->getUser();
        $vote_id = $this->request->param('vote_id');
        $persons = PersonModel::all(['user_id' => $user['id'], 'vote_id' => $vote_id]);
        if ($persons) {
            foreach($persons as &$person){
                $person['images'] = explode(',', $person['images']);
            }
        }
        $this->success('',$persons);
    }

    /**
     * 获取登录用户的作品详情
     */
    public function user_person_detail()
    {
        $user = $this->auth->getUser();
        $person_id = $this->request->param('person_id');
        $person = PersonModel::get(['user_id' => $user['id'], 'id' => $person_id]);
        if ($person) {
            $person['images'] = explode(',', $person['images']);
        }else{
            $this->error('未找到匹配的作品');
        }
        $this->success('',$person);
    }

    /**
     * 报名事件
     */
    public function apply()
    {
        $arr = $this->request->post();
        $vote = VoteModel::get($arr['vote_id']);
        $user = $this->auth->getUser();

        if ($vote['end_apply_status'] == '0') {
            /*
             * 未开启活动结束前均可报名
             * 需要验证报名时间
             */
            if ($vote['apply_start_time'] && time() < $vote['apply_start_time']) {
                $this->error('报名时间未开始');
            }

            if ($vote['apply_end_time'] && time() > $vote['apply_end_time']) {
                $this->error('报名时间已结束');
            }
        } else {
            if ($vote['end_time'] < time()) {
                $this->error('投票活动已结束');
            }
        }

        if (!isset($arr['id']) || !$arr['id']) {
            unset($arr['id']);
            $VotePerson = new PersonModel;
            /*
            if (PersonModel::where(['vote_id' => $arr['vote_id'], 'user_id' => $user['id']])->find()) {
                $this->error('请勿重复报名');
            }
            */
            if ($vote['apply_check'] == '0') {
                // 报名不需要审核
                $arr['status'] = '20';
                $count = $VotePerson->where(['vote_id' => $arr['vote_id']])->where('status', '20')->count();
                $arr['code'] = $count + 1;
            } else {
                $arr['code'] = 1;
                $arr['status'] = '10';
            }

            $arr['type'] = 1;
            $arr['user_id'] = $user['id'];
            $arr['admin_id'] = $vote['admin_id'];
            $VotePerson->allowField(true)->save($arr);
        } else if (isset($arr['id'])) {
            $VotePerson = PersonModel::get($arr['id']);
            $arr['status'] = $vote['apply_check'] == '0' ? '20' : '10';
            $VotePerson->allowField(true)->save($arr);
        }

        if ($VotePerson->id) {
            // 创建活动小程序码
            kzvote_qrCode($VotePerson, $VotePerson['id'], 'pages/vote/person');

            // 发送订阅消息
            if (isset($arr['send']) && $arr['send']){
                if ($this->platform == 'wxapp') {
                    Subscription::apply_success(kzvote_getOpenid($user['id'], $this->platform), 'pages/vote/person?person_id=' . $VotePerson->id, $vote['name'],
                        $vote['start_time_text'] . '~' . $vote['end_time_text'], $vote['apply_check'] == '1' ? '请等待审核' : '报名成功');
                } elseif ($this->platform == 'wechat') {
                    WechatSubscription::apply_success(kzvote_getOpenid($user['id'], $this->platform), 'pages/vote/person?person_id=' . $VotePerson->id, $vote['name'],
                        $vote['start_time_text'] . '~' . $vote['end_time_text'], $vote['apply_check'] == '1' ? '请等待审核' : '报名成功');
                }
            }

            $this->success('报名成功',$VotePerson);
        } else{
            $this->error('报名失败');
        }
    }

    /**
     * 重新生成小程序码
     */
    public function erCode(){
        $id  = $this->request->param('id');
        $model = PersonModel::get($id);
        if (!$model){
            $this->error('作品不存在');
        }
        $model->er_code = '';
        $model->save();
        // 创建活动小程序码
        $url = kzvote_qrCode($model, $model['id'], 'pages/vote/person');
        if ($url){
            $this->success('生成成功',['url' => $url]);
        }
        $this->error('生成失败');
    }

    /**
     * 导出
     */
    public function export()
    {
        set_time_limit(0);

        $vote_id = $this->request->param('vote_id');
        $vote_name = $this->request->param('vote_name');
        $sort = $this->request->param('sort');
        if ($sort == 'code'){
            $order = 'code asc';
        }else{
            $order = 'count desc';
        }

        try {
            //开始制作表格
            $spreadsheet = new Spreadsheet();
            $spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $spreadsheet->getDefaultStyle()->getFont()->setSize(12);
            $spreadsheet->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);
            $spreadsheet->getDefaultStyle()->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
            $spreadsheet->getActiveSheet()->getStyle('J')->getAlignment()->setWrapText(true);

            $worksheet = $spreadsheet->setActiveSheetIndex(0);


            $worksheet->getCell('A1')->setValue('序号');
            $worksheet->getCell('B1')->setValue('作品编号');
            $worksheet->getCell('C1')->setValue('作品名称');
            $worksheet->getCell('D1')->setValue('微信昵称');
            $worksheet->getCell('E1')->setValue('票数');
            $worksheet->getCell('F1')->setValue('分组名称');
            $worksheet->getCell('G1')->setValue('审核状态');
            $worksheet->getCell('H1')->setValue('报名类型');
            $worksheet->getCell('I1')->setValue('报名时间');
            $worksheet->getCell('J1')->setValue('报名选项');

            $ABC = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];

            $list = PersonModel::with(['user'])
                ->where('vote_id',$vote_id)
                ->order($order)
                ->select();

            $arr = [];
            foreach ($list as $key => $val) {

                $option = '';
                if ($val['option']){
                    foreach ($val['option'] as $k => $row) {
                        foreach ($row as $index => $item) {
                            $option .= $index . ":" . $item . "​\n​";
                        }
                    }
                }

                $data = array($val['id'], $val['code'], $val['name'], $val['user']['nickname'], $val['count'], $val['group_name'], $val['status_text'],
                    $val['type_text'], date('Y-m-d H:i:s', $val['createtime']), $option);

                array_push($arr, $data);
            }

            foreach ($arr as $key => $row) {
                foreach ($ABC as $k => $r) {
                    $worksheet->getCell($ABC[$k] . ($key + 2))->setValue($row[$k]);
                }
            }
            $dir = ROOT_PATH . 'public/export/';
            if(!is_dir($dir)){
                mkdir($dir, 0755);
            }
            $dir = ROOT_PATH . 'public/export/person/';
            if(!is_dir($dir)){
                mkdir($dir, 0755);
            }

            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
            $writer->save(ROOT_PATH . 'public/export/person/《' . $vote_name.'》投票作品.xlsx');
            $this->success('导出成功',$this->request->domain().'/export/person/《' . $vote_name.'》投票作品.xlsx');
        }catch (Exception $e){
            $this->error('系统异常');
        }

    }

    /**
     * 生成作品海报
     */
    public function poster()
    {
        $person_id = $this->request->request('id');
        $VotePerson = PersonModel::get($person_id);
        $name = '-' . $VotePerson['name'] . '-';
        $vote_id = $VotePerson['vote_id'];
        $vote = VoteModel::get($vote_id);
        $bg_color = $this->request->param('bg_color', '#d84a41');
        if($this->request->param('is_base', '0') == '0'){

//        $user = $this->auth->getUser();

            if (!$VotePerson['er_code']) {
                $VotePerson['er_code'] = kzvote_qrCode($VotePerson, $VotePerson['id'], 'pages/vote/person');
            }
            $img = [];
//        $img[] = [
//            'url' => cdnurl($user['avatar'], true), // 头像
//            'is_yuan' => true,            // true图片圆形处理
//            'stream' => 0,
//            'left' => -1, // 小于0为小平居中
//            'top' => 30,
//            'right' => 0,
//            'width' => 112, // 图像宽
//            'height' => 112, // 图像高
//            'opacity' => 100, // 透明度
//        ];
            $img[] = [
                'url' => cdnurl($VotePerson['image'], true),
                'is_yuan' => false, // true图片圆形处理
                'stream' => 0,
                'left' => -1, // 小于0为小平居中
                'top' => 30,
                'right' => 0,
                'width' => 540, // 图像宽
                'height' => 400, // 图像高
                'opacity' => 100, // 透明度
                'name' => 'person'
            ];
            $img[] = [
                'url'     => $VotePerson['er_code'],
                'is_yuan' => false, // true图片圆形处理
                'stream' => 0,
                'left' => -1, // 小于0为小平居中
                'top' => 605,
                'right' => 0,
                'width' => 250, // 图像宽
                'height' => 250, // 图像高
                'opacity' => 100, // 透明度
                'name' => 'er_code'
            ];

            $txt = [];
//        $txt[] = [
//            'text' => $user['nickname'], // 昵称
//            'left' => -1,                // 小于0为小平居中
//            'top' => $img[0]['top'] + 160,
//            'fontSize' => 18,            // 字号
//            'fontColor' => '255,255,255', // 字体颜色
//            'angle' => 0,
//        ];
//        $txt[] = [
//            'text' => '邀请您参加投票活动',
//            'left' => -1, // 小于0为小平居中
//            'top' => $img[0]['top'] + 200,
//            'fontSize' => 22,            // 字号
//            'fontColor' => '255,255,255', // 字体颜色
//            'angle' => 0,
//        ];

            // 字符过长，换行
//        if (strlen($vote['name']) > 48) {
//            $name1 = substr($vote['name'], 0, 45);
//            $txt[] = [
//                'text'      => $name1 . ' ...',
//                'left' => -1,     // 小于0为小平居中
//                'top' => 60,
//                'fontSize' => 22,            // 字号
//                'fontColor' => '255,255,255', // 字体颜色
//                'angle' => 0,
//            ];

//            $name2 = substr($vote['name'], 48);
//            $txt[] = [
//                'text' => $name2,// $vote['title'].
//                'left' => -1,     // 小于0为小平居中
//                'top' => $img[0]['top'] + 310,
//                'fontSize' => 20,            // 字号
//                'fontColor' => '105,105,105', // 字体颜色
//                'angle' => 0,
//            ];
//        } else {
//            $txt[] = [
//                'text' => $vote['name'],
//                'left' => -1, // 小于0为小平居中
//                'top' => 60,
//                'fontSize' => 22,            // 字号
//                'fontColor' => '255,255,255', // 字体颜色
//                'angle' => 0,
//            ];
//        }

            $txt[] = [
                'text' => $name,
                'left' => -1, // 小于0为小平居中
                'top' => 490,
                'fontSize' => 22,            // 字号
                'fontColor' => '255,255,255', // 字体颜色
                'angle' => 0,
            ];

            $txt[] = [
                'text'      => '投票时间: '.date('Y-m-d',$vote['start_time']).' ~ '.date('Y-m-d',$vote['end_time']), // 文字内容
                'left'      => -1, // 小于0为小平居中
                'top'       => 540,
                'fontSize'  => 18, // 字号
                'fontColor' => '255,255,255', // 字体颜色
                'angle'     => 0,
            ];

            $txt[] = [
                'text' => '长按或扫码识别参加', // 文字内容
                'left' => -1,          // 小于0为小平居中
                'top' => $img[count($img) - 1]['top'] + 330,
                'fontSize' => 18,            // 字号
                'fontColor' => '255,255,255', // 字体颜色
                'angle' => 0,
            ];
            $txt[] = [
                'text' => '感谢您为我投上珍贵的一票', // 文字内容
                'left' => -1,             // 小于0为小平居中
                'top' => $img[count($img) - 1]['top'] + 380,
                'fontSize' => 18,            // 字号
                'fontColor' => '255,255,255', // 字体颜色
                'angle' => 0,
            ];

            $config = array(
                'image' => $img,
                'text' => $txt,
            );

            // 背景颜色代码转RGB
            $rgba = kzvote_hex2rgba($bg_color, false, true);
            echo Poster::createPoster($config, '', $rgba);
        }else{
            // 二维码目录创建-S
            $voteDir = ROOT_PATH . 'public' . DS . 'vote' . DS . $vote_id;
            $cdnPersonQrcode = $this->request->domain(). DS . 'vote' . DS . $vote_id. DS .$person_id.".png";
            $personQrcode = $voteDir. DS .$person_id.".png";
            if(!is_dir($voteDir)){
                createsysdir($voteDir);
            }
            // 二维码目录创建-E
            // 生成二维码-S
            if(!file_exists($personQrcode)) {
                $params = [
                    'text' => url("/vote", "", false, true)."/#/pages/vote/person?vote_id=".$vote_id."&person_id=".$person_id,
                    'size' => '300',
                    'padding' => '15',
                    'errorlevel' => 'medium',
                    'foreground' => '#000000',
                    'background' => '#ffffff',
                    'logo' => '1',
                    'logosize' => '50',
                    'label' => '',
                    'labelmargin' => '0',
                    'labelfontsize' => '14',
                    'labelalignment' => 'center',
                    'labelfontcolor' => '#000000'
                ];
                $qrCode = \addons\qrcode\library\Service::qrcode($params);
                $qrCode->saveToFile($personQrcode);
            }
            // 生成二维码-E
            if($vote["person_poster"]){
                $posterImgInfo = \app\common\model\Attachment::get(["url"=>$vote["person_poster"]]);
                list($left, $top) = explode(",", $vote["person_qr_pos"]);
                $config = array();
                $img[] = [
                    'url'     => cdnurl($vote["person_poster"], true),
                    'stream'  => 0,
                    'left'    => 0, // 小于0为小平居中
                    'top'     => 0,
                    'width'   => $posterImgInfo->imagewidth, // 图像宽
                    'height'  => $posterImgInfo->imageheight, // 图像高
                    'opacity' => 100, // 透明度
                    'name'    => 'poster_bg'
                ];
                $config['size'] = [
                    'width'   => $posterImgInfo->imagewidth, // 图像宽
                    'height'  => $posterImgInfo->imageheight, // 图像高
                ];
                $img[] = [
                    'url'     => $cdnPersonQrcode,
                    'stream'  => 0,
                    'left'    => $left, // 小于0为小平居中
                    'top'     => $top,
                    'width'   => intval($vote["person_qr_size"]), // 图像宽
                    'height'  => intval($vote["person_qr_size"]), // 图像高
                    'opacity' => 100, // 透明度
                    'name'    => 'poster_bg'
                ];
                if(Poster::kzvote_checkFile(cdnurl($VotePerson['image']))){
                    list($personLeft, $personTop) = explode(",", $vote["person_opus_pos"]);//作品图片中心位置
                    list($personWidth, $personHeight) = getimagesize(cdnurl($VotePerson['image']));
                    // 作品图片尺寸处理-S
                    list($opusWidth, $opusHeight) = explode("x", $vote["person_opus_size"]);//作品图片大小
                    $opusSize = array(
                        'left'    => 0, // 小于0为小平居中
                        'top'     => 0,
                        'width'   => 0, // 图像宽
                        'height'  => 0, // 图像高
                    );
                    if($personWidth > $opusWidth && $personHeight > $opusHeight){
                        // 作品图片尺寸比限定尺寸都大则按照长边等比例缩放-S
                        if($personWidth/$personHeight > $opusWidth/$opusHeight){
                            $ratio = $opusWidth/$personWidth;
                            $opusSize['left'] = $personLeft-intval($opusWidth/2);
                            $opusSize['top'] = $personTop-intval($personHeight*$ratio/2);
                            $opusSize['width'] = $opusWidth;
                            $opusSize['height'] = intval($personHeight*$ratio);
                        }else{
                            $ratio = $opusHeight/$personHeight;
                            $opusSize['left'] = $personLeft-intval($ratio*$personWidth/2);
                            $opusSize['top'] = $personTop-intval($opusHeight/2);
                            $opusSize['width'] = intval($ratio*$personWidth);
                            $opusSize['height'] = $opusHeight;
                        }
                        // 作品图片尺寸比限定尺寸都大则按照长边等比例缩放-E
                    }elseif($personWidth <= $opusWidth && $personHeight <= $opusHeight){
                        // 作品图片尺寸比限定尺寸都小或一致时直接显示-S
                        $opusSize['left'] = $personLeft-intval($personWidth/2);
                        $opusSize['top'] = $personTop-intval($personHeight/2);
                        $opusSize['width'] = $personWidth;
                        $opusSize['height'] = $personHeight;
                        // 作品图片尺寸比限定尺寸都小或一致时直接显示-E
                    }else{
                        // 作品图片尺寸只有一边符合限定尺寸按最大边等比例缩放-S
                        if($personWidth > $opusWidth && $personHeight < $opusHeight){
                            $ratio = $opusWidth/$personWidth;
                            $opusSize['left'] = $personLeft-intval($opusWidth/2);
                            $opusSize['top'] = $personTop-intval($ratio*$opusHeight/2);
                            $opusSize['width'] = $opusWidth;
                            $opusSize['height'] = intval($ratio*$opusHeight);
                        }else{
                            $ratio = $opusHeight/$personHeight;
                            $opusSize['left'] = $personLeft-intval($ratio*$opusWidth/2);
                            $opusSize['top'] = $personTop-intval($opusHeight/2);
                            $opusSize['width'] = intval($ratio*$opusWidth);
                            $opusSize['height'] = $opusHeight;
                        }
                        // 作品图片尺寸只有一边符合限定尺寸按最大边等比例缩放-E
                    }
                    // 作品图片尺寸处理-S
                    $img[] = array_merge([
                        'url'     => cdnurl($VotePerson['image']),
                        'stream'  => 0,
                        'opacity' => 100, // 透明度
                        'name'    => 'poster_opus'
                    ], $opusSize);
                }else{
                    echo "获取参赛作品图错误";
                }
                $config['image'] = $img;
                list($nameLeft, $nameTop) = explode(",", $vote["person_name_pos"]);
                list($numLeft, $numTop) = explode(",", $vote["person_num_pos"]);
                // 作品名称处理-S
                $nameFontSize = 28;//字体大小
                $nameLetterSpace = 7;//字间距
                $nameLineSpace = 14;//行间距
                $nameTxtMaxWidth = $config["size"]["width"] - $nameLeft*2;//单行最大字数
                $i=0;//渲染行索引
                $tmpWidth = 0;//当前行临时宽度
                $tmpStrArr = [];//当前行临时字符集
                $strArr = mb_str_split($name, 1);//将需要渲染的作品名称按单字分割成数组
                $finalStrArr = [];
                foreach($strArr as $index=>$char){
                    //计算当前文字像素宽度-S
                    $box = imagettfbbox($nameFontSize, 0, ROOT_PATH . 'public/assets/fonts/HarmonyOS_Sans_SC_Bold.ttf', $char);
                    $currentStrWidth = $box[2] - $box[0] + $nameLetterSpace;
                    //计算当前文字像素宽度-E
                    if(($index+1) == count($strArr)){
                        //最后一个文字处理-S
                        if(($tmpWidth+$currentStrWidth) > $nameTxtMaxWidth){
                            //加上最后一个字宽度越界需要对最后一个字符单独换行特殊处理-S
                            $finalStrArr[] = implode("", $tmpStrArr);
                            ++$i;
                            $finalStrArr[] = $char;
                            //加上最后一个字宽度越界需要对最后一个字符单独换行特殊处理-E
                        }else{
                            //加上最后一个字宽度未越界直接渲染-E
                            $tmpStrArr[] = $char;
                            $finalStrArr[] = implode("", $tmpStrArr);
                            //加上最后一个字宽度未越界直接渲染-E
                        }
                        //最后一个文字处理-E
                    }else{
                        if(($tmpWidth+$currentStrWidth) > $nameTxtMaxWidth){
                            //加上当前字符越界需要将之前的进行渲染并对当前字符进行换行处理-S
                            $finalStrArr[] = implode("", $tmpStrArr);
                            $tmpStrArr = [$char];//当前行重置
                            ++$i;//渲染行增加
                            $tmpWidth = $currentStrWidth;//临时宽度重置
                            //加上当前字符越界需要将之前的进行渲染并对当前字符进行换行处理-S
                        }else{
                            $tmpWidth += $currentStrWidth;//临时宽度累加
                            $tmpStrArr[] = $char;//增加当前行临时字符
                        }
                    }
                }
                foreach($finalStrArr as $fIndex=>$fVal){
                    $txt[] = [
                        'text' => $fVal,
                        'left' => $nameLeft*-1, // 小于0为小平居中
                        'top' => $nameTop-((count($finalStrArr)-$fIndex-1) * ($nameFontSize+$nameLineSpace)),
                        'fontSize' => $nameFontSize,// 字号
                        'fontColor' => '26,26,26', // 字体颜色
                        'angle' => 0,
                        'ttf' => 'HarmonyOS_Sans_SC_Bold.ttf'
                    ];
                }
                $txt[] = [
                    'text' => "{$VotePerson['code']}",
                    'left' => $numLeft, // 小于0为小平居中
                    'top' => $numTop,
                    'fontSize' => 20,            // 字号
                    'fontColor' => '118,118,118', // 字体颜色
                    'angle' => 0,
                ];
                $config['text'] = $txt;
                // 背景颜色代码转RGB
                $rgba = kzvote_hex2rgba($bg_color, false, true);
                $content = Poster::createQrPoster($config, '', $rgba);
                return response($content, 200, ['Content-type' => "image/png" ]);
            }else{
                echo "获取配置错误";
            }
        }
    }

}
